/**
 * Copyright 2013-2022 the original author or authors from the Jeddict project (https://jeddict.github.io/).
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package io.github.jeddict.jpa.modeler.specification.model.workspace;

import java.awt.Component;
import java.util.List;
import static java.util.stream.Collectors.toList;
import javax.swing.AbstractListModel;
import javax.swing.DefaultListSelectionModel;
import javax.swing.JCheckBox;
import javax.swing.JList;
import javax.swing.JOptionPane;
import static javax.swing.JOptionPane.WARNING_MESSAGE;
import static javax.swing.JOptionPane.showMessageDialog;
import javax.swing.ListCellRenderer;
import io.github.jeddict.jpa.spec.EntityMappings;
import io.github.jeddict.jpa.spec.workspace.WorkSpace;
import io.github.jeddict.jpa.modeler.initializer.JPAModelerScene;
import org.netbeans.modeler.properties.window.GenericDialog;
import static org.openide.util.NbBundle.getMessage;
import org.openide.windows.WindowManager;

/**
 *
 * @author jGauravGupta
 */
public class WorkSpaceTrashDialog extends GenericDialog {

    private final List<WorkSpace> workSpaces;
    private final EntityMappings entityMappings;
    private final JPAModelerScene scene;
    private boolean currentWorkSpaceDeleted;


    /**
     * Creates new form WorkSpaceTrashDialog
     */
    public WorkSpaceTrashDialog(JPAModelerScene scene) {
        this.scene = scene;
        this.entityMappings = scene.getBaseElementSpec();
        this.workSpaces = entityMappings.getWorkSpaces()
                .stream()
                .filter(wp -> wp != entityMappings.getRootWorkSpace())
                .collect(toList());
        initComponents();
    }

    public List<WorkSpace> getSelectedWorkSpace() {
        return workSpaceList.getSelectedValuesList();
    }
    
    /**
     * @return the currentWorkSpaceDeleted
     */
    public boolean isCurrentWorkSpaceDeleted() {
        return currentWorkSpaceDeleted;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        workSpaceList = new javax.swing.JList<>();
        action_LayeredPane = new javax.swing.JLayeredPane();
        save_Button = new javax.swing.JButton();
        cancel_Button = new javax.swing.JButton();
        globalSelectCheckBox = new javax.swing.JCheckBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(org.openide.util.NbBundle.getMessage(WorkSpaceTrashDialog.class, "WorkSpaceTrashDialog.title")); // NOI18N

        workSpaceList.setCellRenderer(new CheckboxListCellRenderer());
        workSpaceList.setSelectionModel(new DefaultListSelectionModel() {
            @Override
            public void setSelectionInterval(int index0, int index1) {
                if(super.isSelectedIndex(index0)) {
                    super.removeSelectionInterval(index0, index1);
                }
                else {
                    super.addSelectionInterval(index0, index1);
                }
            }
        });
        workSpaceList.setBackground(new java.awt.Color(250, 250, 250));
        workSpaceList.setModel(getWorkSpaceModel());
        workSpaceList.setToolTipText(org.openide.util.NbBundle.getMessage(WorkSpaceTrashDialog.class, "WorkSpaceTrashDialog.workSpaceList.toolTipText")); // NOI18N
        jScrollPane1.setViewportView(workSpaceList);

        org.openide.awt.Mnemonics.setLocalizedText(save_Button, org.openide.util.NbBundle.getMessage(WorkSpaceTrashDialog.class, "WorkSpaceTrashDialog.save_Button.text")); // NOI18N
        save_Button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                save_ButtonActionPerformed(evt);
            }
        });
        setDefaultButton(save_Button);

        org.openide.awt.Mnemonics.setLocalizedText(cancel_Button, org.openide.util.NbBundle.getMessage(WorkSpaceTrashDialog.class, "WorkSpaceTrashDialog.cancel_Button.text")); // NOI18N
        cancel_Button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancel_ButtonActionPerformed(evt);
            }
        });

        action_LayeredPane.setLayer(save_Button, javax.swing.JLayeredPane.DEFAULT_LAYER);
        action_LayeredPane.setLayer(cancel_Button, javax.swing.JLayeredPane.DEFAULT_LAYER);

        javax.swing.GroupLayout action_LayeredPaneLayout = new javax.swing.GroupLayout(action_LayeredPane);
        action_LayeredPane.setLayout(action_LayeredPaneLayout);
        action_LayeredPaneLayout.setHorizontalGroup(
            action_LayeredPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(action_LayeredPaneLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(save_Button)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cancel_Button)
                .addGap(12, 12, 12))
        );
        action_LayeredPaneLayout.setVerticalGroup(
            action_LayeredPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(action_LayeredPaneLayout.createSequentialGroup()
                .addGroup(action_LayeredPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(save_Button)
                    .addComponent(cancel_Button))
                .addGap(0, 8, Short.MAX_VALUE))
        );

        org.openide.awt.Mnemonics.setLocalizedText(globalSelectCheckBox, org.openide.util.NbBundle.getMessage(WorkSpaceTrashDialog.class, "WorkSpaceTrashDialog.globalSelectCheckBox.text")); // NOI18N
        globalSelectCheckBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                globalSelectCheckBoxActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(globalSelectCheckBox)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(action_LayeredPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 303, Short.MAX_VALUE)
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 312, Short.MAX_VALUE)
                .addGap(25, 25, 25)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(action_LayeredPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(globalSelectCheckBox)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private boolean validateField() {
        if (getSelectedWorkSpace().isEmpty()) {
            showMessageDialog(this, "No workspace selected!", "Empty Selection", WARNING_MESSAGE);
            return false;
        }
        return true;
    }
    
    private void save_ButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_save_ButtonActionPerformed
        if (!validateField()) {
            return;
        }
        int option = JOptionPane.showConfirmDialog(
                WindowManager.getDefault().getMainWindow(),
                getMessage(WorkSpaceTrashDialog.class, "WorkSpaceTrashDialog.delete.selected.content"),
                getMessage(WorkSpaceTrashDialog.class, "WorkSpaceTrashDialog.delete.selected.title"),
                JOptionPane.YES_NO_OPTION);
        if (option == javax.swing.JOptionPane.OK_OPTION) {
            currentWorkSpaceDeleted = entityMappings.removeAllWorkSpace(getSelectedWorkSpace());
            scene.getModelerPanelTopComponent().changePersistenceState(false);
            saveActionPerformed(evt);
        }
    }//GEN-LAST:event_save_ButtonActionPerformed

    private void cancel_ButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancel_ButtonActionPerformed
        cancelActionPerformed(evt);
    }//GEN-LAST:event_cancel_ButtonActionPerformed

    private void globalSelectCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_globalSelectCheckBoxActionPerformed
       if(globalSelectCheckBox.isSelected()){
           workSpaceList.setSelectionInterval(0, workSpaceList.getModel().getSize()-1);
       } else {
           workSpaceList.clearSelection();
       }
    }//GEN-LAST:event_globalSelectCheckBoxActionPerformed

    private AbstractListModel<WorkSpace> getWorkSpaceModel() {
        return new AbstractListModel<WorkSpace>() {
            @Override
            public int getSize() {
                return workSpaces.size();
            }

            @Override
            public WorkSpace getElementAt(int i) {
                return workSpaces.get(i);
            }
        };
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLayeredPane action_LayeredPane;
    private javax.swing.JButton cancel_Button;
    private javax.swing.JCheckBox globalSelectCheckBox;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton save_Button;
    private javax.swing.JList<WorkSpace> workSpaceList;
    // End of variables declaration//GEN-END:variables
}

class CheckboxListCellRenderer extends JCheckBox implements ListCellRenderer {

    @Override
    public Component getListCellRendererComponent(JList list, Object value, int index,
            boolean isSelected, boolean cellHasFocus) {
        setComponentOrientation(list.getComponentOrientation());
        setFont(list.getFont());
        setBackground(list.getBackground());
        setForeground(list.getForeground());
        setSelected(isSelected);
        setEnabled(list.isEnabled());
        setText(value == null ? "" : value.toString());
        return this;
    }
}
